package com.medical.app.controller;

import com.medical.app.dto.request.HealthRecordRequest;
import com.medical.app.dto.request.HeightWeightRequest;
import com.medical.app.dto.request.StepsRequest;
import com.medical.app.dto.request.SleepRequest;
import com.medical.app.dto.response.ApiResponse;
import com.medical.app.entity.HealthRecord;
import com.medical.app.entity.User;
import com.medical.app.service.HealthRecordService;
import com.medical.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/health-records")
@CrossOrigin(origins = "*")
public class HealthRecordController {

    @Autowired
    private HealthRecordService healthRecordService;

    @Autowired
    private UserService userService;

    // 整体保存或更新健康记录
    @PostMapping
    public ResponseEntity<ApiResponse<HealthRecord>> saveHealthRecord(@RequestBody HealthRecordRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            HealthRecord healthRecord = new HealthRecord();
            healthRecord.setRecordDate(request.getRecordDate() != null ? request.getRecordDate() : LocalDate.now());
            healthRecord.setHeight(request.getHeight());
            healthRecord.setWeight(request.getWeight());
            healthRecord.setSteps(request.getSteps());
            healthRecord.setSleepHours(request.getSleepHours());
            healthRecord.setUser(user.get());

            HealthRecord savedRecord = healthRecordService.saveOrUpdateHealthRecord(healthRecord);
            return ResponseEntity.ok(ApiResponse.success("保存成功", savedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 单独更新身高体重
    @PostMapping("/height-weight")
    public ResponseEntity<ApiResponse<HealthRecord>> updateHeightWeight(@RequestBody HeightWeightRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            LocalDate recordDate = request.getRecordDate() != null ? request.getRecordDate() : LocalDate.now();
            HealthRecord savedRecord = healthRecordService.updateHeightWeight(
                    request.getUserId(),
                    request.getHeight(),
                    request.getWeight(),
                    recordDate
            );

            return ResponseEntity.ok(ApiResponse.success("身高体重保存成功", savedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 单独更新步数
    @PostMapping("/steps")
    public ResponseEntity<ApiResponse<HealthRecord>> updateSteps(@RequestBody StepsRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            LocalDate recordDate = request.getRecordDate() != null ? request.getRecordDate() : LocalDate.now();
            HealthRecord savedRecord = healthRecordService.updateSteps(
                    request.getUserId(),
                    request.getSteps(),
                    recordDate
            );

            return ResponseEntity.ok(ApiResponse.success("步数保存成功", savedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 单独更新睡眠时间
    @PostMapping("/sleep")
    public ResponseEntity<ApiResponse<HealthRecord>> updateSleep(@RequestBody SleepRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            LocalDate recordDate = request.getRecordDate() != null ? request.getRecordDate() : LocalDate.now();
            HealthRecord savedRecord = healthRecordService.updateSleepHours(
                    request.getUserId(),
                    request.getSleepHours(),
                    recordDate
            );

            return ResponseEntity.ok(ApiResponse.success("睡眠时间保存成功", savedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 其他方法保持不变...
    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<HealthRecord>>> getUserHealthRecords(@PathVariable Long userId) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            List<HealthRecord> records = healthRecordService.getUserHealthRecords(userId);
            return ResponseEntity.ok(ApiResponse.success(records));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/user/{userId}/latest")
    public ResponseEntity<ApiResponse<HealthRecord>> getLatestHealthRecord(@PathVariable Long userId) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            Optional<HealthRecord> record = healthRecordService.getLatestHealthRecord(userId);
            if (record.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success(record.get()));
            } else {
                return ResponseEntity.ok(ApiResponse.success("暂无健康记录", null));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/user/{userId}/recent/{days}")
    public ResponseEntity<ApiResponse<List<HealthRecord>>> getRecentHealthRecords(
            @PathVariable Long userId,
            @PathVariable int days) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            List<HealthRecord> records = healthRecordService.getRecentHealthRecords(userId, days);
            return ResponseEntity.ok(ApiResponse.success(records));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/user/{userId}/date-range")
    public ResponseEntity<ApiResponse<List<HealthRecord>>> getHealthRecordsByDateRange(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            List<HealthRecord> records = healthRecordService.getHealthRecordsByDateRange(userId, startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success(records));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteHealthRecord(@PathVariable Long id) {
        try {
            healthRecordService.deleteHealthRecord(id);
            return ResponseEntity.ok(ApiResponse.success("删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}